package cn.tedu._05weibo.common.exception;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import springfox.documentation.spring.web.json.Json;

import javax.validation.ConstraintViolationException;


/**
 * ControllerAdvice注解：
 * 1.将此类标识为全局异常处理类；
 * 2.一旦控制中抛出了异常，则框架首先会检查有没有定义全局异常处理器；
 *   2.1 定义了：则由全局异常处理器处理异常.
 *   2.2 未定义：则使用Spring MVC默认的异常处理机制[不友好].
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     *ExceptionHandler注解：标识此方法为一场处理方法
     */
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
        /*
            ex.getMessage()方法：获取异常提示消息;
         */
        log.error("IllegalArgumentException = " + ex.getMessage());
        // {"state": 2002, "message": "操作失败", "data": "ID值不能小于0"}
        return new JsonResult(StatusCode.OPERATION_FAILED, ex.getMessage());
    }

    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex){
        log.error("RuntimeException = " + ex.getMessage());
        return new JsonResult(StatusCode.OPERATION_FAILED, ex.getMessage());
    }

    /**
     * Validation验证框架异常:DTO类方式数据校验
     */
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String message = ex.getFieldError().getDefaultMessage();
        log.error("message = " + message);

        // {"state": 3001, "message": "参数校验失败", "data":"用户名不能为空值"}
        return new JsonResult(StatusCode.VALIDATED_ERROR, message);
    }

    @ExceptionHandler
    public JsonResult doHandle(ConstraintViolationException ex){
        String message = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException = " + message);
        return new JsonResult(StatusCode.VALIDATED_ERROR, message);
    }
}
